package com.example.saifly.inPageRecord;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.R;
import com.example.saifly.inPageRecord.RecordModel.BodyData;
import com.hb.dialog.myDialog.MyAlertInputDialog;

import java.io.IOException;
import java.util.Date;

import cn.qqtheme.framework.picker.NumberPicker;
import cn.qqtheme.framework.picker.OptionPicker;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class WriteBodyActivity extends Activity {

    private TextView tvCarbonDioxide,tvHighBloodPressure;//tv展示各项指标
    private TextView tvBloodOxygen,tvLowBloodPressure,tvBloodOxygenPressure;
    private TextView tvTemperature,tvStep,tvHeart;

    private RelativeLayout rlCarbonDioxide,rlHighBloodPressure;//tv展示各项指标
    private RelativeLayout rlBloodOxygen,rlLowBloodPressure,rlBloodOxygenPressure;
    private RelativeLayout rlTemperature,rlStep,rlHeart;

    private ImageView ivReturn;

    private Button btSubmit;//提交录入的信息
    private int bloodOxygen,carbonDioxide,highBloodPressure,lowBloodPressure,step,bloodOxygenPressure;//获取环境指标
    private int heart;
    private float temperature;//获取体温，动脉血氧分压
    private BodyData bodyData= new BodyData();//身体数据信息实体
    private SharedPreferences sharedPreferences;
    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_write_body_data;
    }

    @Override
    protected void init() {
        super.init();

        sharedPreferences= MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);

        tvBloodOxygen=findViewById(R.id.blood_oxygen_word);
        tvTemperature=findViewById(R.id.temperature_word);
        tvBloodOxygenPressure=findViewById(R.id.blood_oxygen_pressure_word);
        tvCarbonDioxide=findViewById(R.id.carbon_dioxide_word);
        tvHighBloodPressure=findViewById(R.id.high_blood_Pressure_word);
        tvLowBloodPressure=findViewById(R.id.low_blood_Pressure_word);
        tvStep=findViewById(R.id.step_word);
        tvHeart=findViewById(R.id.heart_word);

        rlBloodOxygen=findViewById(R.id.write_body_data_blood_oxygen);
        rlTemperature=findViewById(R.id.write_body_data_temperature);
        rlBloodOxygenPressure=findViewById(R.id.write_data_body_blood_oxygen_pressure);
        rlCarbonDioxide=findViewById(R.id.write_body_data_carbon_dioxide);
        rlHighBloodPressure=findViewById(R.id.write_data_body_high_blood_Pressure);
        rlLowBloodPressure=findViewById(R.id.write_data_body_low_blood_Pressure);
        rlStep=findViewById(R.id.write_data_body_step);
        rlHeart=findViewById(R.id.write_data_body_heart);
        ivReturn=findViewById(R.id.write_body_data_return);
        btSubmit=findViewById(R.id.write_body_data_submit);

        rlHighBloodPressure.setOnClickListener(new addListeners());
        rlLowBloodPressure.setOnClickListener(new addListeners());
        rlBloodOxygenPressure.setOnClickListener(new addListeners());
        rlBloodOxygen.setOnClickListener(new addListeners());
        rlCarbonDioxide.setOnClickListener(new addListeners());
        UpdateUi();
        btSubmit.setOnClickListener(new addListeners());
        doJump();

    }

    private  void doJump()
    {

        ivReturn.setOnClickListener(view -> finish());
        rlStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(WriteBodyActivity.this).builder()
                        .setTitle("请输入")
                        .setEditText("");
                myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int temp=0;
                        for(int i=0;i<myAlertInputDialog.getResult().length();i++)
                        {
                            if(myAlertInputDialog.getResult().charAt(i)>='0'&&myAlertInputDialog.getResult().charAt(i)<='9')
                            {

                            }
                            else
                            {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(WriteBodyActivity.this, "步数格式不正确", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                temp=1;
                            }
                        }
                        if(temp==0)
                        {
                            int steptemp=Integer.parseInt(myAlertInputDialog.getResult());
                            sharedPreferences.edit().putString("step",String.valueOf(steptemp));
                            tvStep.setText(String.valueOf(steptemp)+"步");
                            doUpdate();
                            myAlertInputDialog.dismiss();
                        }
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        myAlertInputDialog.dismiss();
                    }
                });
                myAlertInputDialog.show();
            }
        });

        rlTemperature.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(WriteBodyActivity.this).builder()
                        .setTitle("请输入")
                        .setEditText("");
                myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int temp=0;
                        for(int i=0;i<myAlertInputDialog.getResult().length();i++)
                        {
                            if(myAlertInputDialog.getResult().charAt(i)>='0'&&myAlertInputDialog.getResult().charAt(i)<='9')
                            {

                            }
                            else if(myAlertInputDialog.getResult().charAt(i)=='.')
                            {

                            }
                            else
                            {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(WriteBodyActivity.this, "体温格式不正确", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                temp=1;
                            }
                        }
                        float tempHeat;
                        if(temp==0)
                        {
                            tempHeat=Float.parseFloat(myAlertInputDialog.getResult());

                            if(tempHeat>=34.0&&tempHeat<=45.0)
                            {
                                tvTemperature.setText(String.valueOf(tempHeat)+"℃");
                                doUpdate();
                                myAlertInputDialog.dismiss();
                            }
                            else
                            {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(WriteBodyActivity.this, "体温数值不正确", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }


                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        myAlertInputDialog.dismiss();
                    }
                });
                myAlertInputDialog.show();
            }
        });

        rlHeart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(WriteBodyActivity.this).builder()
                        .setTitle("请输入")
                        .setEditText("");
                myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int temp=0;
                        for(int i=0;i<myAlertInputDialog.getResult().length();i++)
                        {
                            if(myAlertInputDialog.getResult().charAt(i)>='0'&&myAlertInputDialog.getResult().charAt(i)<='9')
                            {

                            }
                            else
                            {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(WriteBodyActivity.this, "心率格式不正确", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                temp=1;
                            }
                        }
                        if(temp==0)
                        {
                            int hearttemp=Integer.parseInt(myAlertInputDialog.getResult());

                            if(hearttemp>=30&&hearttemp<=200)
                            {
                                tvHeart.setText(String.valueOf(hearttemp)+"次/分钟");
                                doUpdate();
                                myAlertInputDialog.dismiss();
                            }
                            else
                            {
                                Toast.makeText(WriteBodyActivity.this, "心率范围不正确", Toast.LENGTH_SHORT).show();
                            }

                        }
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        myAlertInputDialog.dismiss();
                    }
                });
                myAlertInputDialog.show();
            }
        });

    }



    /**
     * 创建日期：2019/12/7 17:41
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明： 血氧饱和度选择器
     */
    private void initBloodOxygenPicker() {
        NumberPicker bloodOxygenPicker = new NumberPicker(this);

        bloodOxygenPicker.setOffset(2);//偏移量
        bloodOxygenPicker.setRange(50, 100);//数字范围
        bloodOxygenPicker.setSelectedItem(95);
        bloodOxygenPicker.setLabel("%");
        bloodOxygenPicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener()
        {
            @Override
            public void onOptionPicked(String option)
            {
                tvBloodOxygen.setText(option+"%");
            }
        });
        bloodOxygenPicker.show();

    }


    /**
     * 创建日期：2019/12/7 17:41
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明：动脉血氧分压选择器
     */

    private void initBloodOxygenPressurePicker() {

        NumberPicker highBloodOxygenPressurePicker = new NumberPicker(this);
        highBloodOxygenPressurePicker.setOffset(2);//偏移量
        highBloodOxygenPressurePicker.setRange(60, 150);//数字范围
        highBloodOxygenPressurePicker.setSelectedItem(90);
        highBloodOxygenPressurePicker.setLabel("mmHg");
        highBloodOxygenPressurePicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option)
            {
                tvBloodOxygenPressure.setText(option+"mmHg");
            }
        });
        highBloodOxygenPressurePicker.show();

    }
    /**
     * 创建日期：2019/12/7 17:41
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明：血压高压选择器
     */
    private void initHighBloodPressurePicker() {
        NumberPicker highBloodPressurePicker = new NumberPicker(this);
        highBloodPressurePicker.setOffset(2);//偏移量
        highBloodPressurePicker.setRange(60, 260);//数字范围
        highBloodPressurePicker.setSelectedItem(120);
        highBloodPressurePicker.setLabel("mmHg");
        highBloodPressurePicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option)
            {
                tvHighBloodPressure.setText(option+"mmHg");
            }
        });
        highBloodPressurePicker.show();
    }


    /**
     * 创建日期：2019/12/7 17:41
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明：血压低压选择器
     */
    private void initLowBloodPressurePicker() {
        NumberPicker lowBloodPressurePicker = new NumberPicker(this);
        lowBloodPressurePicker.setOffset(2);//偏移量
        lowBloodPressurePicker.setRange(40, 120);//数字范围
        lowBloodPressurePicker.setSelectedItem(80);
        lowBloodPressurePicker.setLabel("mmHg");
        lowBloodPressurePicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option)
            {
                tvLowBloodPressure.setText(option+"mmHg");
            }
        });
        lowBloodPressurePicker.show();
    }
    /**
     * 创建日期：2019/12/7 17:41
     * @author Yuan Li Xiang
     * @version 1.0
     * 类说明：血压高压选择器
     */
    private void initCarbonDioxidePicker() {
        NumberPicker carbonDioxidePicker = new NumberPicker(this);
        carbonDioxidePicker.setOffset(2);//偏移量
        carbonDioxidePicker.setRange(20, 60);//数字范围
        carbonDioxidePicker.setSelectedItem(40);
        carbonDioxidePicker.setLabel("mmHg");
        carbonDioxidePicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option)
            {
                tvCarbonDioxide.setText(option+"mmHg");
            }
        });
        carbonDioxidePicker.show();
    }

    private int getIntegerDate(String str)
    {
        int temp;
        String tmp="";
        for(int i=0;i<str.length();i++)
        {
            if (str.charAt(i)<='9'&&str.charAt(i)>='0') {
                tmp+=str.charAt(i);
            }
            else
            {
                break;
            }
        }

        temp=Integer.parseInt(tmp);
        return temp;
    }

    private float getFloatDate(String str)
    {
        float temp;
        String tmp="";
        for(int i=0;i<str.length();i++)
        {
            if (str.charAt(i)<='9'&&str.charAt(i)>='0') {
                tmp+=str.charAt(i);
            }
            else if(str.charAt(i)=='.')
            {
                tmp+=str.charAt(i);
            }
            else
            {
                break;
            }
        }
            temp=Float.parseFloat(tmp);
            return temp;

    }

    private  void analyse() {
        step=getIntegerDate(tvStep.getText().toString());
        heart=getIntegerDate(tvHeart.getText().toString());
        temperature = getFloatDate(tvTemperature.getText().toString());
        bloodOxygen = getIntegerDate(tvBloodOxygen.getText().toString());
        carbonDioxide = getIntegerDate(tvCarbonDioxide.getText().toString());
        highBloodPressure = getIntegerDate(tvHighBloodPressure.getText().toString());
        lowBloodPressure = getIntegerDate(tvLowBloodPressure.getText().toString());
        bloodOxygenPressure = getIntegerDate(tvBloodOxygenPressure.getText().toString());

    }

    private interface ApiBodySetData
    {
        @Headers({"Content-Type:application/json"})
        @POST("/plan/submitBodyData")
        Call<ResponseBody> BodySetData(@Body JSONObject jsonObject);

        @Headers({"Content-Type:application/json"})
        @POST("/estimate/getBodyData")
        Call<ResponseBody> BodyGetData(@Body JSONObject jsonObject);


    }

    private void BodySetData(BodyData bodyData)
    {
        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();
        ApiBodySetData apiBodySetData=retrofit.create(ApiBodySetData.class);

        JSONObject jsonObject=new JSONObject();
        String jsonString = JSON.toJSONString(bodyData);
        jsonObject.put("bodyData",jsonString);
        Log.d("bodyData", "BodySetData: "+jsonObject.toString());

        Call<ResponseBody> call=apiBodySetData.BodySetData(jsonObject);//请求
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                    //  dailyQesFinish = (int) result.get("result");
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(WriteBodyActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(WriteBodyActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }

    }
    private void BodyGetData(String phoneNum,Date date)
    {
        Long longDate =date.getTime();
        RetrofitHelper retrofitHelper =new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiBodySetData apiBodySetData = retrofit.create(ApiBodySetData.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("patientPhone",phoneNum);
        jsonObject.put("date",longDate);

        Call <ResponseBody> call = apiBodySetData.BodyGetData(jsonObject);

        final Response<ResponseBody> response;

        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                    //  dailyQesFinish = (int) result.get("result");


                    JSONObject resultbodyData =result.getJSONObject("result");
                    String bodyDate=resultbodyData.getString("bodyData");
                    BodyData bodyData =JSON.parseObject(bodyDate, BodyData.class);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d("bodydata", "run: "+bodyData.toString());
                            tvTemperature.setText( String.valueOf(bodyData.getBodyTemperature())+ "℃");
                            tvBloodOxygen.setText(bodyData.getBloodOxygen().toString()+"%");
                            tvBloodOxygenPressure.setText(bodyData.getBloodOxygenPressure().toString() + "mmHg");
                            tvCarbonDioxide.setText(bodyData.getCarbonPressure().toString()+"mmHg");
                            tvHeart.setText(bodyData.getHeartRate().toString() + "次/分钟");
                            tvHighBloodPressure.setText(bodyData.getHeightBloodPressure().toString()+"mmHg");
                            tvLowBloodPressure.setText(bodyData.getLowBloodPressure().toString() + "mmHg");
                            tvStep.setText(bodyData.getStepCount().toString()+"步");

                        }
                    });
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(WriteBodyActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(WriteBodyActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }


    }
    private  void  UpdateUi()
    {
        SharedPreferences sharedPreferences = MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);
        String phoneNum = sharedPreferences.getString("uid","default");
        Date date = new Date();

        new Thread(new Runnable() {
            @Override
            public void run() {
                BodyGetData(phoneNum,date);
            }
        }).start();

    }

    private class addListeners implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.write_body_data_carbon_dioxide:
                    initCarbonDioxidePicker();
                    doUpdate();
                    break;
                case R.id.write_body_data_blood_oxygen:
                    initBloodOxygenPicker();
                    doUpdate();
                    break;

                case R.id.write_body_data_submit:

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(WriteBodyActivity.this, "信息已保存", Toast.LENGTH_SHORT).show();
                        }
                    });

                    doUpdate();
//                    analyse();
//
//                    String phoneNum = sharedPreferences.getString("uid", "default");
//                    bodyData.setPatientPhone(phoneNum);
//                    bodyData.setBodyTemperature(temperature);
//                    bodyData.setStepCount(step);
//                    bodyData.setBloodOxygen(bloodOxygen);
//                    bodyData.setCarbonPressure(carbonDioxide);
//                    bodyData.setBloodOxygenPressure(bloodOxygenPressure);
//                    bodyData.setHeightBloodPressure(highBloodPressure);
//                    bodyData.setLowBloodPressure(lowBloodPressure);
//                    bodyData.setHeartRate(heart);
//
//                    Date date = new Date();
//
//                    bodyData.setDate(date);
////                    ScoreBodyEnvironment scoreBodyEnvironment=new ScoreBodyEnvironment();
////                    scoreBodyEnvironment.setBodyData(bodyData);
////                    int score = scoreBodyEnvironment.bodyScore();
////                    Log.d("score", "score:"+score);
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            BodySetData(bodyData);
//                        }
//                    }).start();
                    WriteBodyActivity.this.finish();
                    break;

                case R.id.write_data_body_blood_oxygen_pressure:
                    initBloodOxygenPressurePicker();
                    doUpdate();
                    break;
                case R.id.write_data_body_high_blood_Pressure:
                    initHighBloodPressurePicker();
                    doUpdate();
                    break;
                case R.id.write_data_body_low_blood_Pressure:
                    initLowBloodPressurePicker();
                    doUpdate();
                    break;
                default:
                    break;
            }
        }
    }

    private void doUpdate()
    {
        analyse();

        String phoneNum = sharedPreferences.getString("uid", "default");
        bodyData.setPatientPhone(phoneNum);
        bodyData.setBodyTemperature(temperature);
        bodyData.setStepCount(step);
        bodyData.setBloodOxygen(bloodOxygen);
        bodyData.setCarbonPressure(carbonDioxide);
        bodyData.setBloodOxygenPressure(bloodOxygenPressure);
        bodyData.setHeightBloodPressure(highBloodPressure);
        bodyData.setLowBloodPressure(lowBloodPressure);
        bodyData.setHeartRate(heart);

        Date date = new Date();

        bodyData.setDate(date);
//                    ScoreBodyEnvironment scoreBodyEnvironment=new ScoreBodyEnvironment();
//                    scoreBodyEnvironment.setBodyData(bodyData);
//                    int score = scoreBodyEnvironment.bodyScore();
//                    Log.d("score", "score:"+score);
        new Thread(new Runnable() {
            @Override
            public void run() {
                BodySetData(bodyData);
            }
        }).start();

    }
}
